<?php

namespace App\Http\Controllers\Api\v2;

use App\Alipay\Alipay;
use App\Http\Controllers\ApiController;
use App\Models\Order;

class AlipayController extends ApiController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function sign()
    {
        $order_id = $this->request->input('order_id');
        $order = Order::with('trade')->find($order_id);

        $params = Alipay::pay()->appPay([
            'subject'=>$order->trade->subject,
            'out_trade_no'=>$order->trade->out_trade_no,
            'total_amount'=>$order->trade->total_amount
        ]);
        return ajaxReturn(['payStr'=>http_build_query($params)]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function query()
    {
        $out_trade_no = '';
        $result = $this->request->input('result');
        $order_id = $this->request->input('order_id');
        if ($order_id) {
            $out_trade_no = Order::find($order_id)->order_no;
        } else {
            $result = json_decode($result, true);
            if (isset($result['alipay_trade_app_pay_response'])){
                $out_trade_no = $result['alipay_trade_app_pay_response']['out_trade_no'];
            }
        }

        if ($out_trade_no) {
            if (Alipay::pay()->query(['out_trade_no'=>$out_trade_no])->tradeSuccess()) {
                $order = Order::where('order_no', $out_trade_no)->first();
                if ($order) {
                    $order->update([
                        'pay_status'=>1,
                        'pay_at'=>time(),
                        'updated_at'=>time(),
                        'trade_status'=>2
                    ]);
                    $order->trade()->update([
                        'pay_type'=>'alipay',
                        'pay_status'=>1,
                        'pay_at'=>time(),
                        'updated_at'=>time(),
                        'trade_status'=>2
                    ]);
                    $order->actions()->insert([
                        'order_id'=>$order->order_id,
                        'uid'=>$this->uid,
                        'username'=>$this->username,
                        'content'=>trans('mall.pay success'),
                        'created_at'=>time()
                    ]);
                }
            }
        }

        return ajaxReturn(['trade_no'=>$out_trade_no]);
    }
}
